package com.lxy.user.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.facebody20191230.models.CompareFaceResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.teautil.Common;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxy.common.constant.ResponseConstant;
import com.lxy.common.domain.common.R;
import com.lxy.user.ai.CompareFace;
import com.lxy.user.domain.po.UserFace;
import com.lxy.user.mapper.UserFaceMapper;
import com.lxy.user.service.UserFaceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserFaceServiceImpl extends ServiceImpl<UserFaceMapper, UserFace> implements UserFaceService {
    @Override
    public R<Long> face(MultipartFile file) throws Exception {
        // 创建AccessKey ID和AccessKey Secret，请参考https://help.aliyun.com/document_detail/175144.html
        // 如果您使用的是RAM用户的AccessKey，还需要为子账号授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        com.aliyun.facebody20191230.Client client = CompareFace.createClient(accessKeyId, accessKeySecret);
        //查询人脸库，进行比对
        List<UserFace> userFaces = list();
        if (userFaces.isEmpty()) {
            return R.error("人脸库为空");
        }
        // 读取上传文件到字节数组（只需读取一次）
        byte[] fileBytes = file.getBytes();
        for (UserFace userFace : userFaces) {
            // 每次循环创建新的输入流（从内存字节数组读取）
            InputStream inputStreamA = new ByteArrayInputStream(fileBytes);
            URL url = new URL(userFace.getFace());
            InputStream inputStreamB = url.openConnection().getInputStream();
            com.aliyun.facebody20191230.models.CompareFaceAdvanceRequest compareFaceAdvanceRequest = new com.aliyun.facebody20191230.models.CompareFaceAdvanceRequest()
                    .setImageURLAObject(inputStreamA)
                    .setImageURLBObject(inputStreamB);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            try {
                CompareFaceResponse compareFaceResponse = client.compareFaceAdvance(compareFaceAdvanceRequest, runtime);
                // 获取整体结果
                String jsonString = Common.toJSONString(TeaModel.buildMap(compareFaceResponse));
                //解析json
                JSONObject jsonObject = JSONObject.parseObject(jsonString);
                JSONObject body = jsonObject.getJSONObject("body");
                JSONObject data = body.getJSONObject("Data");
                double confidence = data.getDoubleValue("Confidence");
                //设置阈值为69
                if(confidence>69){
                    return R.ok(userFace.getUserId());
                }
            } catch (TeaException teaException) {
                // 获取整体报错信息
                System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
                // 获取单个字段
                System.out.println(teaException.getCode());
                return R.error("未识别到人脸，请重试");
            }
        }
        return R.error(ResponseConstant.NOT_ALLOW);
    }
}
